package com.jhws.business.local.service;

import com.alibaba.fastjson.JSON;
import com.jhws.business.local.bo.LocalConstant;
import com.jhws.business.owner.bo.TblOwnerDimBo;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.core.db.BaseDao;
import com.jhws.util.LogHelper;
import com.jhws.util.net.JhHttpClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class OwnerSynchService {
    @Resource
    private BaseDao BaseDao;

    public void saveOwner(TblOwnerDimBo ownerDimBo) {
        ownerDimBo.setIsSynch(LocalConstant.SYNCH_STATE_YES);
        BaseDao.saveOrUpdate(ownerDimBo);
    }

    public void deleteOwner(TblOwnerDimBo tblOwnerDimBo) throws Exception {
        BaseDao.delete(tblOwnerDimBo);
    }

    public List<TblOwnerDimBo> findTblOwnerDimByWhere(String whereStr) throws Exception {
        return BaseDao.findList("from TblOwnerDimBo " + whereStr);
    }

    public void mergeOwner(String serverUrl, String commCode, Map<String, String> headers) throws Exception {
        List<TblOwnerDimBo> list = findTblOwnerDimByWhere("where comm_code = '" + commCode + "' and is_synch != '" + LocalConstant.SYNCH_STATE_YES + "'");
        if (list == null || list.isEmpty()) {
            return;
        }
        JhHttpClient hp = new JhHttpClient();
        for (TblOwnerDimBo ownerDimBo : list) {
            String s = hp.postJson(serverUrl + "api/localSynch/owner/owners", JSON.toJSONString(ownerDimBo), headers);
            LogHelper.d("-------------------->    " + s);
            try {
                JsonRespData respData = JSON.parseObject(s, JsonRespData.class);
                if (respData.ret_code > 0) {
                    if (ownerDimBo.getIsSynch() == LocalConstant.SYNCH_STATE_NO) {
                        saveOwner(ownerDimBo);
                    } else if (ownerDimBo.getIsSynch() == LocalConstant.SYNCH_STATE_DEL) {
                        deleteOwner(ownerDimBo);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
